package cg.cmm.gateway.filter;

import cg.cmm.gateway.props.AuthProperties;
import cg.cmm.toolkic.utils.JwtTokenUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * token权限校验&白名单过滤
 *
 * @author yingxli
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired(required = false)
    private AuthProperties authProperties;

    @Resource
    private ObjectMapper objectMapper;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Resource
    private JwtTokenUtils jwtTokenUtil;

    public static final String AUTH_KEY = "token";


    /**
     * token验证解析，判断是否是白名单内的请求，如果是需要跳过token验证
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (shouldSkip(path)) {
            return chain.filter(exchange);
        }

        ServerHttpResponse resp = exchange.getResponse();

        String headerToken = exchange.getRequest().getHeaders().getFirst(AUTH_KEY);
        if (StringUtils.isBlank(headerToken)) {
            return unAuth(resp, "缺失令牌,鉴权失败");
        }

        if (!jwtTokenUtil.checkToken(headerToken)) {
            return unAuth(resp, "令牌校验失败");
        }

        // 验证通过
        return chain.filter(exchange);
    }

    private boolean shouldSkip(String path) {
        return Optional.ofNullable(authProperties).map(o -> o.getSkipUrl().stream()
                .anyMatch(pattern -> antPathMatcher.match(pattern, path))).orElse(true);
    }

    private Mono<Void> unAuth(ServerHttpResponse resp, String msg) {
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String result = "";
        try {
            result = objectMapper.writeValueAsString(response(401, msg));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
        DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

    /**
     * 构建返回的JSON数据格式
     *
     * @param status  状态码
     * @param message 信息
     * @return
     */
    public static Map<String, Object> response(int status, String message) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", status);
        map.put("msg", message);
        map.put("data", null);
        return map;
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
